package com.wuhuahe.luanfeng.netty.example.rpc;

import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.ZooDefs;
import org.apache.zookeeper.ZooKeeper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.List;
import java.util.concurrent.CountDownLatch;

/**
 * Created By wuhuahe
 * author:游龙
 * Date: 2018-07-14
 * Time: 17:02
 * Desc:
 */
public class ServiceCenter {
    private static final Logger LOGGER = LoggerFactory.getLogger(ServiceCenter.class);

    private static final String APPS_PATH = "/__apps__";
    private static ZooKeeper zk;

    private static void connect() throws InterruptedException, KeeperException, IOException {
        if (zk != null) {
            return;
        }
        CountDownLatch latch = new CountDownLatch(1);
        //服务中心地址，从配置文件读取
        String serverCenterAddress = "localhost";

        zk = new ZooKeeper(serverCenterAddress, 30000, null);
        latch.await();
        if (zk.exists(APPS_PATH, false) == null) {
            zk.create(APPS_PATH, null, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
        }
    }

    public static void register(String serviceName, String address) {
        try {
            connect();
            if (zk.exists(APPS_PATH + "/" + serviceName, false) == null) {
                zk.create(APPS_PATH + "/" + serviceName, null, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
            }
            String path = zk.create(APPS_PATH + "/" + serviceName + "/", address.getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL_SEQUENTIAL);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (KeeperException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public String queryService(String serviceName) throws KeeperException, InterruptedException {
        List<String> apps = zk.getChildren(APPS_PATH + "/" + serviceName, false);
        if (apps.isEmpty()) {
            return null;
        }
        //Collections.sort(apps);
        byte[] data = zk.getData(apps.get(0), false, null);
        return new String(data);
    }

}
